export function Connection(vm) {

	return {
		bluetoothArr: [],
		deviceId: 0,
		dataInfo: {},
		returnMessage: '',
		onLoad() {
			// let buf = this.str2ab("$DATA0:1243,54,12");
			// let str = this.ab2str(buf)
			// console.log(str)
			// console.log('App onLoad');
			// 在页面加载时候初始化蓝牙适配器
			uni.openBluetoothAdapter({
				success: (e) => {
					// 初始化完毕
					if (e.errMsg == "openBluetoothAdapter:ok") {
						uni.getConnectedBluetoothDevices({
							services: [],
							success: (res) => {
								if (res.devices.length) {
									console.log("初始化完毕", JSON.stringify(res.devices))
								} else {
									this.startBluetoothDevicesDiscovery()
								}
							}
						})

					}
				},
				fail: (e) => {
					if (e.errCode == 10001) {
						uni.showModal({
							title: 'Tips',
							content: this.i18n.msg35 || 'Please Turn On Bluetoot And Connect The Device',
							showCancel: false,
							success: (res) => {
								uni.removeStorageSync("left")
								// if (res.confirm) {
								// 	uni.navigateBack({
								// 		delta: 1
								// 	})
								// }
							}
						});
					}
				}
			});
			uni.onBLEConnectionStateChange((res) => {
				// 该方法回调中可以用于处理连接意外断开等异常情况
				console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)

				if (!res.connected) {
					uni.closeBLEConnection({
						deviceId: res.deviceId,
						success: res => {
							if (this.bluetoothArrWatch) {
								this.bluetoothArrWatch(this.bluetoothArr);
							}
							console.log(res);
						}
					})
					this.deviceId = 0;

					uni.$emit('closeClick', res.deviceId)
				}
			})
		},
		startBluetoothDevicesDiscovery() {
			//在页面显示的时候判断是都已经初始化完成蓝牙适配器若成功，则开始查找设备
			uni.startBluetoothDevicesDiscovery({
				services: ["FFE0"],
				success: res => {
					if (res.errMsg == "startBluetoothDevicesDiscovery:ok") {
						this.onBluetoothDeviceFound();
					}

				},
				fail: res => {
					console.log("查找设备失败", res)
					uni.showToast({
						icon: "none",
						title: "Failed to find device！",
						duration: 3000
					})
				}
			});
		},
		/**
		 * 停止搜索蓝牙设备
		 */
		stopBluetoothDevicesDiscovery() {
			uni.stopBluetoothDevicesDiscovery({
				success: e => {
					console.log('停止搜索蓝牙设备:' + e.errMsg);
				},
				fail: e => {
					console.log('停止搜索蓝牙设备失败，错误码：' + e.errCode);
				}
			});
		},
		/**
		 * 发现外围设备
		 */
		onBluetoothDeviceFound() {
			uni.onBluetoothDeviceFound(devices => {
				this.getBluetoothDevices();
			});
		},
		/**
		 * 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
		 */
		getBluetoothDevices() {
			uni.getBluetoothDevices({
				success: (res) => {
					let bluetooth = [];

					// console.log("查找到的设备", JSON.stringify(res.devices))
					let deviceIdOk = false;
					res.devices.forEach(item => {


						if (item.name && item.name.toLowerCase().includes("smart")) {
							item.name = item.name.replace("SmartFoot", "SmartBoot");
							bluetooth.push(item);
							if (item.deviceId === this.deviceId) {
								deviceIdOk = true;
							}
						}
					});
					if (!deviceIdOk && this.bluetoothArr.length) {
						for (let obj of this.bluetoothArr) {
							if (obj.deviceId === this.deviceId) {
								bluetooth.push(obj);
								break;
							}
						}
					}
					this.bluetoothArr = bluetooth;
					if (this.bluetoothArrWatch) {
						this.bluetoothArrWatch(bluetooth);
					}
					console.log("设备数量", bluetooth.length)
					//尝试连接过历史连接的蓝牙设备
					bluetooth.forEach((item, index) => {
						if (item.deviceId == uni.getStorageSync('oldleft')) {
							this.createBLEConnection(item.deviceId);
							if (!uni.getStorageSync("left")) {
								uni.setStorageSync("left", uni.getStorageSync('oldleft'))
							}
						}
					})
				}
			});
		},
		//断开蓝牙连接
		closeBLEConnection(deviceId) {
			uni.closeBLEConnection({
				deviceId: deviceId,
				success: res => {
					this.deviceId = 0;
					if (uni.getStorageSync('left') == deviceId) {
						uni.removeStorageSync("left")
						uni.removeStorageSync("oldleft")
					}
				}
			})
		},
		// 连接蓝牙设备
		createBLEConnection(deviceId, successCallBack) {
			this.deviceId = deviceId;
			if (this.bluetoothArrWatch) {
				this.bluetoothArrWatch(this.bluetoothArr);
			}

			uni.createBLEConnection({
				deviceId: this.deviceId,
				success: res => {
					uni.showLoading({
						title: "Loading..."
					});
					setTimeout(function() {
						uni.hideLoading();
					}, 3500);
					this.dataInfo = {
						dataBuff: '',
						$INFO: [],
						$DATA0: [],
						$DATA1: [],
						$DATA2: [],
						$DATA3: [],
						$DATA4: [],
						$DATA5: [],
						$DATA6: [],
						$TOTAL: [],
						$WEIGHT: [],
						sendTime: false,
						saveTime: 0
					}
					this.getBLEDeviceServices(this.deviceId);
					uni.setBLEMTU({
						deviceId: this.deviceId,
						mtu: 100,
						success: e => {
							console.log("uni.setBLEMTU success")
						},
						fail: e => {
							console.log("uni.setBLEMTU fail")
						}
					})
					uni.setStorageSync("bluetooth.joinTime", new Date().getTime())
					if (successCallBack) {
						successCallBack();
					}
				},
				fail: res => {
					console.error("连接蓝牙设备 失败")
				}
			})
		},
		//获取蓝牙设备所有服务(service)。
		getBLEDeviceServices(deviceId) {
			setTimeout(() => {
				uni.getBLEDeviceServices({
					deviceId: deviceId,
					success: (res) => {
						this.serverList = res.services
						res.services.forEach((item) => {
							if (item.uuid.indexOf("FFE0") != -1) {
								this.serviceId = item.uuid;
								this.getBLEDeviceCharacteristics(this.deviceId)
							}
						})
					}
				})
			}, 3000)
		},

		// 获取蓝牙特征值
		getBLEDeviceCharacteristics(deviceId) {
			setTimeout(() => {
				uni.getBLEDeviceCharacteristics({
					deviceId: deviceId,
					serviceId: this.serviceId,
					success: (res) => {
						console.log("获取蓝牙特征值", JSON.stringify(res))
						this.characteristics = res.characteristics
						res.characteristics.forEach((item) => {
							console.log("###", item)
							if (item.uuid.indexOf("FFE1") != -1) {
								this.characteristicId = item.uuid;
								console.log('characteristicId:', this.characteristicId)
								this.notifyBLECharacteristicValueChange(this.deviceId)
							}
						})
					},
					fail: (res) => {
						console.log(res)
					}
				})
			}, 3000)
		},
		// 启用 notify 功能
		notifyBLECharacteristicValueChange(deviceId) {
			uni.notifyBLECharacteristicValueChange({
				state: true, // 启用 notify 功能
				deviceId: deviceId,
				serviceId: this.serviceId,
				characteristicId: this.characteristicId,
				success: (res) => {
					console.log('notifyBLECharacteristicValueChange success', res.errMsg)

					this.onBLECharacteristicValueChange(this.deviceId);
				},
				fail: (res) => {
					console.log('notifyBLECharacteristicValueChange success', res.errMsg)
				}
			})
		},
		// 监听低功耗蓝牙设备的特征值变化
		onBLECharacteristicValueChange(deviceId) {
			uni.onBLECharacteristicValueChange((res) => {
				// console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
				// console.log('监听低功耗蓝牙设备的特征值变化:' + this.ab2str(res.value), res.value.byteLength)
				this.analysisData(this.ab2str(res.value), res.deviceId)
			})
		},
		ab2str(buf) {
			return String.fromCharCode.apply(null, new Uint8Array(buf));
		},
		// 读取设备二进制数据
		readBLECharacteristicValue() {
			uni.readBLECharacteristicValue({
				deviceId: this.deviceId,
				serviceId: this.serviceId,
				characteristicId: this.characteristicId,
				success: (res) => {
					console.log('readBLECharacteristicValue:', res)
					this.readCode = res.errCode;
					this.readCodeMsg = res.errMsg;
					this.onBLECharacteristicValueChange(this.deviceId);
				},
				fail: (res) => {
					console.log('readBLECharacteristicValue:', res)
					this.readCode = res.errCode;
					this.readCodeMsg = res.errMsg;
					this.onBLECharacteristicValueChange(this.deviceId);
				}
			})
		},
		str2ab(str) {
			let buf = new ArrayBuffer(str.length); // 每个字符占用2个字节
			let bufView = new Uint8Array(buf);
			for (let i = 0; i < str.length; i++) {
				bufView[i] = str.charCodeAt(i);
			}
			return buf;
		},
		sendStr(str, successFun) {
			if (!this.deviceId) {
				console.error("未连接设备")
				return
			}
			this.writeBLECharacteristicValue(str, successFun);
		},
		// 发送数据
		writeBLECharacteristicValue(str, successFun) {
			let buffer = this.str2ab(str)
			if (vm.$utils.isDebug) {
				uni.showToast({
					icon: "none",
					title: str,
					duration: 3300
				})
			}

			console.log("发送数据:" + str, buffer.byteLength, this.characteristicId)
			uni.writeBLECharacteristicValue({
				deviceId: this.deviceId,
				serviceId: this.serviceId,
				characteristicId: this.characteristicId,
				value: buffer,
				success: (res) => {
					this.returnMessage = res.errMsg;
					if (successFun) {
						successFun();
					}
					console.log('writeBLECharacteristicValue success', res.errMsg)
				},
				fail: (res) => {
					this.returnMessage = res.errMsg;
					console.log('writeBLECharacteristicValue fail', res.errMsg)
				}
			})
		},
		sendTimeDo() {
			if (!this.dataInfo.sendTime) {
				let tmpStr = "$TIM:," + vm.$utils.formatDate(new Date(), "YYMMDD,HHmmss") + ";";
				setTimeout(() => {
					this.writeBLECharacteristicValue(tmpStr)
				}, 1000)
				// this.writeBLECharacteristicValue(tmpStr.substring(0,10))
				// setTimeout(()=>{
				// 	this.writeBLECharacteristicValue(tmpStr.substring(10))
				// },1000)
				this.dataInfo.sendTime = true;
			}
		},
		analysisData(data, deviceId) {
			if (!data) {
				return
			}
			let now = new Date().getTime()
			// console.log(data + "                                   #")
			let dataBuff = this.dataInfo.dataBuff + data
			if (!dataBuff.startsWith("$")) {
				let arr = dataBuff.split("$");
				if (arr && arr.length > 1) {
					dataBuff = "$" + arr[1]
				}
			}
			let pos = dataBuff.indexOf(";")
			if (pos === -1) {
				this.dataInfo.dataBuff = dataBuff
				return;
			}
			this.dataInfo.dataBuff = dataBuff.substring(pos)
			let value = dataBuff.substring(0, pos)
			// if (value && !value.startsWith("$DATA") &&  !value.startsWith("$TOTAL")) {
				// console.log("接收数据:" + value + "                     ")

			// }


			let tmpArr = value.split(":")
			if (tmpArr.length === 2) {
				let dataArr = tmpArr[1].split(",")
				this.dataInfo[tmpArr[0]] = dataArr
			}
			let isOk = true;
			if (this.dataInfo.$INFO.length !== 5) {
				isOk = false;
			}
			if (this.dataInfo.$DATA0.length !== 11) {
				isOk = false;
			}
			if (this.dataInfo.$DATA1.length !== 11) {
				isOk = false;
			}
			if (this.dataInfo.$DATA2.length !== 11) {
				isOk = false;
			}
			if (this.dataInfo.$DATA3.length !== 11) {
				isOk = false;
			}
			if (this.dataInfo.$DATA4.length !== 11) {
				isOk = false;
			}
			if (this.dataInfo.$DATA5.length !== 11) {
				isOk = false;
			}
			if (this.dataInfo.$DATA6.length !== 11) {
				isOk = false;
			}
			if (this.dataInfo.$TOTAL.length !== 7) {
				isOk = false;
			}
			// if (value.startsWith("$WEIGHT")) {
			// 	this.dataInfo.$WEIGHT = value
			// }
			if (isOk && value.startsWith("$TOTAL")) {
				this.dataInfo.saveTime = now
				uni.setStorageSync("bluetooth.dataInfo", this.dataInfo)
				this.sendTimeDo()

			}
			if (value && (value.startsWith("$WEIGHT") || value.startsWith("$DATA0"))) {
				  uni.setStorageSync("bluetooth.$WEIGHT", this.dataInfo)

			}
		}
	}
}
